import time
import datetime
import re
import sys

import numpy as np
from selenium import webdriver
from PIL import Image

from selenium.webdriver import ChromeOptions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

sys.path.append('../')
import manual

executable_path = './driver/phantomjs'
service_log_path = './log/ghostdriver.log'
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0')
if manual.mode == 1:
    driver = webdriver.PhantomJS(
        executable_path=executable_path,
        service_log_path=service_log_path,
        desired_capabilities=dcap,
        service_args=['--ignore-ssl-errors=true', '--debug=true', '--ssl-protocol=any']
        )
elif manual.mode == 2:
    driver = webdriver.Firefox()
elif manual.mode == 3:
    driver = webdriver.PhantomJS(executable_path='./driver/phantomjs.exe')


'''
2-民生银行；
3-汇丰银行；
4-建设银行；
5-兴业银行；
6-浦发银行；
7-光大银行；
8-广州银行；
9-平安银行；
10-上海银行；
11-中国银行；
12-交通银行；
13-招商银行；
14-广发银行；
15-中信银行;
16-工商银行；
17-华夏银行;
'''

urls = {
    'url0':'localhost:'+manual.ports[0],
    'url_02':'https://kefu.creditcard.cmbc.com.cn/wdxykindex.shtml?age=11#dingWeiAllByHSY',#民生银行
    'url_03':'https://creditcards.hsbc.com.cn/perbank/bk0321/home/cardquery/cardquery',#汇丰银行
    'url_05':'https://personalbank.cib.com.cn/pers/creditCard/outer/querySchedule.do', #兴业银行
    'url_06':'https://www.spdbccc.com.cn/spdb/cupd/applyProgress.do?method=index', #浦发银行
    'url_08':'http://trip.cupdata.com/weixin/webApply.do?action=applyProgressInit&bankNum=6413&userId=o37EKjx_oc_tZT81BEp1sYjypFyc',#广州银行
    'url_09':'https://c.pingan.com/apply/newpublic/credit_card_query/index.html#index', #平安银行
    'url_10':('https://mbank.bankofshanghai.com/pweixin/static/'
              'index.html?Page=uz0TG5NcEjUM5dh+CrCOUtztX6sHP4/5vvt/cDOxiB'
              'z6tgf7pKrBwxPpaZvzHT8ONE/97VEcp2aGEuI9tH4HiNIF4q1LTVHjoOs5o/'
              'I2vCOCx2+bn0jR7cSeoEnvRIj3vaPxophoEWg99Tj53W67b6D6fPgwPhlLGuDS0iK/'
              'kCZpiapoYkeAjffu7EFacAQU1ceZEss2hfNJRqe02Gkv9q3n8s376jBRQR5B'
              'EEZmTTQQPftoTQ986Q3gltyLbrqINeo9ez3kvk9DbFn9YWwUp4uDhhT6OKRB'
              'SpXF9dvGCRkqU02980bvM3KWnkytAFYa0+dew8M1xQXAxucK5yiYPO35Z+pvE7S8'),
              #上海银行
    'url_12':'https://creditcardapp.bankcomm.com/member/apply/status/preinquiry.html',#交通银行
    'url_15':(
        'https://creditcard.ecitic.com/citiccard/online/'
        'firstPageManage.do?func=applyProcessQry#'), #中信银行
    'url_17':'https://creditcloud.hxb.com.cn/hxypt/CridetCardApplySchedule.do?_locale=zh_CN&LoginType=C'#华夏银行
}

opt_series_number = 1000000

def de_alert():
    try:
        alert = driver.switch_to.alert
        alert.accept()
    except:
        pass

def go_back():
    de_alert()
    driver.get(urls['url0'])
    return 0

def get_opt(optname):
    global opt_series_number
    mode = 1
    opt_series_number += 1
    opt_file_name = './static/'+str(opt_series_number)+'.png'
    while(mode == 1):
        driver.get_screenshot_as_file('./static/screen.png')
        location = driver.find_element_by_xpath(optname).location
        size = driver.find_element_by_xpath(optname).size
        left = location['x']
        top = location['y']
        right = location['x']+size['width']
        bottom = location['y']+size['height']
        opt = Image.open('./static/screen.png')
        im = opt.crop((left, top, right, bottom))
        if np.mean(np.array(im)) != 255.0:
            mode = 0
    im.save(opt_file_name)
    return manual.current_domain_name + opt_file_name[1:]

def new_page(url):
    global driver
    try:
        driver.get(url)
    except:
        #driver = webdriver.PhantomJS(executable_path=executable_path,service_log_path=service_log_path,desired_capabilities=dcap,service_args=['--ignore-ssl-errors=true', '--debug=true', '--ssl-protocol=any'])
        #driver = webdriver.PhantomJS()
        #driver = webdriver.Chrome()
        #driver.get(url)
        pass

def parse(series, mode, bank, idNo, phoneNo, optNo, verifyNo):
    t = time.localtime(time.time())
    receive_time = str(t.tm_year) + '-' + str(t.tm_mon) + '-' + str(t.tm_mday) + ' ' + str(t.tm_hour) + ':' + str(t.tm_min) + ':' + str(t.tm_sec)
    message = {
        'serialNo':series,
        'responseCode':None,
        'receiveTime':receive_time,
        'responseTime':'',
        'imageUrl':None,
        'resultCode':None,
        'textAll':None,
    }
    crawler = [900000, None, None]
    if bank == 0:
        pass
    elif bank == 2:
        if mode == 1:
            crawler = minsheng_1(optNo, verifyNo)
        elif mode == 2:
            crawler = minsheng_2()
            message['imageUrl'] = crawler[2]
        elif mode == 3:
            crawler = minsheng_3(idNo)
    elif bank ==3:
        if mode == 1:
            crawler = huifeng_1(verifyNo)
        elif mode == 2:
            crawler = huifeng_2()
            message['imageUrl'] = crawler[2]
        elif mode == 3:
            crawler = huifeng_3(idNo,optNo)
    elif bank == 5:#兴业银行
        if mode == 1:
            crawler = xingye_1(idNo)
    elif bank == 6:#浦发银行
        if mode == 1:
            crawler = pufa_1(idNo, optNo)
        elif mode == 2:
            crawler = pufa_2()
            message['imageUrl'] = crawler[2]
    elif bank == 8:#广州银行
        if mode == 1:
            crawler = guangzhou_1(idNo)
        #elif mode == 2:
        #    crawler = guangzhou_2()
        #    message['imageUrl'] = crawler[2]
    elif bank == 9:#平安银行
        if mode == 1:
            crawler = pingan_1(verifyNo)
        elif mode == 3:
            crawler = pingan_3(idNo, phoneNo)
    elif bank == 10:#上海银行
        if mode == 1:
            crawler = shanghai_1(idNo)
    elif bank == 12:#交通银行
        if mode == 1:
            crawler = jiaotong_1(idNo, optNo)
        elif mode ==2:
            crawler = jiaotong_2()
            message['imageUrl'] = crawler[2]
    elif bank == 15:#中信银行
        if mode == 1:
            crawler = zhongxin_1(verifyNo)
        elif mode == 3:
            crawler = zhongxin_3(idNo, phoneNo)
    elif bank == 17:#华夏银行
        if mode == 1:
            crawler = huaxia_1(idNo, optNo)
        elif mode == 2:
            crawler = huaxia_2()
            message['imageUrl'] = crawler[2]
    else:
        crawler = [900000, None, None]
    message['responseCode'] = crawler[0]
    message['resultCode'] = crawler[1]
    message['textAll'] = crawler[2]
    t = time.localtime(time.time())
    feedback_time = str(t.tm_year) + '-' + str(t.tm_mon) + '-' + str(t.tm_mday) + ' ' + str(t.tm_hour) + ':' + str(t.tm_min) + ':' + str(t.tm_sec)
    message['responseTime'] = feedback_time
    return message

#2：民生银行
def minsheng_2():
    de_alert()
    new_page(urls['url_02'])
    locator = (By.XPATH, '//*[@id="verifyImg"]')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.visibility_of_element_located(locator))
        opt_dir = get_opt('//*[@id="verifyImg"]')
    except:
        return [900002, None, None]
    return [1, None, opt_dir]

def minsheng_3(idNo):
    if driver.current_url != urls['url_02']:
        return [0, None, None]
    else:
        js = 'document.getElementById("sid").value = ' + '"' + idNo + '"'
        driver.execute_script(js)
        js = 'document.getElementById("getApplyMailBtn").click()'
        driver.execute_script(js)
        time.sleep(2)
        msg = driver.find_element_by_id('mailOrPhoneCodeTitleInWz').get_attribute('innerText')
        if '请留意查收' not in msg:
            return[900004, None, None]
    return [1, None, msg]

def minsheng_1(optNo, verifyNo):
    if driver.current_url != urls['url_02']:
        return [900000,None,None]
    else:
        js = 'document.getElementById("extracode").value = ' + '"' + optNo + '"'
        driver.execute_script(js)
        js = 'document.getElementById("messageCode").value = '+ '"' + verifyNo + '"'
        driver.execute_script(js)
        js = 'document.getElementsByClassName("btn")[11].click()'
        driver.execute_script(js)
        try:
            locator = (By.XPATH,'//*[@id="isLogon2"]')
            WebDriverWait(driver, 5, 0.5).until(EC.visibility_of_element_located(locator))
        except:
            try:
                driver.find_element_by_xpath('//*[@id="alertFram2"]/div[2]/button').click()
            except:
                pass
            return [900003,None,None]
        text = driver.find_element_by_xpath('//*[@id="isLogon2"]').find_element_by_class_name('table').text.split()
        detail = {}
        for i in range(1,len(text)//3):
            detail[str(i-1)] = {}
            detail[str(i-1)]['card_type'] = text[3*i+0]
            detail[str(i-1)]['time'] = text[3*i+1]
            detail[str(i-1)]['text'] = text[3*i+2]
        code = 2
        for key,values in detail.items():
            if values['text'] == '已产生卡片':
                day = time.mktime(time.strptime(values['time'],'%Y-%m-%d'))
                d_day = time.time()-day
                if d_day//86400 < 90:
                    code == 1
                    break
        return [1,code,detail]

#3:汇丰银行
def huifeng_1(verifyNo):
    driver.find_element_by_xpath('//*[@id="smscode"]').send_keys(verifyNo)
    driver.find_element_by_xpath('//*[@id="main"]/div[1]/div/div[2]/input').click()
    locator = (By.XPATH, '//*[@id="main"]/div[2]/div/input')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.visibility_of_element_located(locator))
    except:
        return [900001, None, None]
    html = driver.page_source
    pattern = re.compile('<td>(.+?)<\/td>')
    info = pattern.findall(html)
    detail = {}
    for i in range(int(len(info)/6)):
        detail[str(i)] = {}
        detail[str(i)]['text'] = info[6*i+5]
        detail[str(i)]['time'] = info[6*i+0]
        detail[str(i)]['card_type'] = info[6*i+3]
    code = 2
    for key,values in detail.items():
        if  '恭喜您！' in values['text']:
            day = time.mktime(time.strptime(values['time'], '%Y-%m-%d'))
            d_day = time.time() - day
            if d_day//86400 < 90:
                code = 1
                break
    return [1,code,detail]

def huifeng_2():
    de_alert()
    new_page(urls['url_03'])
    locator = (By.XPATH, '//*[@id="main"]/div[1]/div/div[2]/input')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.visibility_of_element_located(locator))
    except:
        return [900001, None, None]
    opt_dir = get_opt('//*[@id="pwPic"]')
    return [1,None,opt_dir]

def huifeng_3(idNo,optNo):
    if driver.current_url != urls['url_03']:
        return [900000, None, None]
    try:
        driver.find_element_by_xpath('//*[@id="idNo"]').clear()
        driver.find_element_by_xpath('//*[@id="idNo"]').send_keys(idNo)
        driver.find_element_by_xpath('//*[@id="code"]').clear()
        driver.find_element_by_xpath('//*[@id="code"]').send_keys(optNo)
        driver.find_element_by_xpath('//*[@id="smsbt"]').click()
    except:
        return [900000,None,None]
    time.sleep(2)
    de_alert()
    try:
        if driver.find_element_by_xpath('//*[@id="main"]/div[1]/div/div[1]/table/tbody/tr[2]/td[2]/span[1]').is_displayed():
            return [900003,None,None]
    except:
        pass
    return [1,None,None]

#5：兴业银行    
def xingye_1(idno):
    de_alert()
    new_page(urls['url_05'])
    locator = (By.NAME,'method:query')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))   
    except Exception as e:
        driver.get(urls['url0'])
        return [900001,None,None]
    try: 
        driver.find_element_by_name('certNo').clear()
        driver.find_element_by_name('certNo').send_keys(idno)
        driver.find_element_by_name('method:query').click()
    except:
        return [900000,None,None]
    time.sleep(0.5)
    try:
        message = driver.find_element_by_class_name('cib-dialog-msg')
        message = message.text
        go_back()
        return [1, 3, None]
    except:
        pass
    try:
        pageid = driver.find_element_by_xpath('//*[@id="pageNo"]')
        if pageid.text == '页面编号： 00190000_B':
            locator = (By.XPATH,'//*[@id="form_0"]')
            try:
                WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
            except:
                driver.get(urls['url0'])
                return [900001,None,None] 
            #nameid = driver.find_element_by_xpath('//*[@id="form"]/div[1]/div[1]/div')
            #name = nameid.text
            statusid = driver.find_element_by_xpath('//*[@id="form"]/div[1]/div[2]/div')
            message = statusid.text
            go_back()
            detail = {'0':{'text':message}}
            if message == '审核通过':
                return [1, 1, detail]
            else:
                return [1, 2, detail]
    except:
        go_back()
        return [900000, None, None] 
#广州银行

def guangzhou_1(idNo):
    new_page(urls['url_08'])
    driver.find_element_by_xpath('//*[@id="idNo"]').send_keys(idNo)
    driver.find_element_by_xpath('/html/body/div[2]/div[2]/form/div[1]/input').click()
    time.sleep(2)
    info = driver.find_element_by_xpath('//*[@id="qryList"]').text
    code = 2
    if '审核完成' in info:
        if info.split('\n')[7] == '审核完成':
            daystr = info.split('\n')[3]
            day = time.mktime(time.strptime(daystr, '%Y-%m-%d'))
            d_day = time.time()-day
            if d_day//86400 < 90:
                code = 1
            return [1, code,'']
        else:
            return [1, code, '']
    elif '未能审批' in info:
        return [1, code, '']
    else:
        return [1, 3, '']

#9：平安银行
def pingan_3(idNo,phoneNo):
    de_alert()
    new_page(urls['url_09'])
    locator = (By.ID,'getOtp')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
    except:
        driver.get(urls['url0'])
        return [900001,None,None]
    try:
        driver.find_element_by_name('idNo').send_keys(idNo)
        driver.find_element_by_name('phoneId').send_keys(phoneNo)
        btn = driver.find_element_by_id('getOtp')
        if btn.get_attribute('value') == '获取动态码':
            btn.click()
        else:
            return [900004,None,None]
        time.sleep(2)
        if btn.get_attribute('value') == '获取动态码':
            return [900004,None,None]
        else:
            return [1,None,None]
    except:
        return [900000,None,None]

def pingan_1(verifyNo):
    if driver.current_url != urls['url_09']:
        return [900000,None,None]
    try:
        driver.find_element_by_name('cardID').clear()
        driver.find_element_by_name('cardID').send_keys(verifyNo)
        driver.find_element_by_id('submitBtn').click()
    except:
        return [900000,None,None]
    time.sleep(0.5)
    if driver.current_url == urls['url_09']:
        return [900005,None,None]
    elif driver.current_url == 'https://c.pingan.com/apply/newpublic/credit_card_query/index.html#goNoRecord':
        return [1,3,None]
    else:
        locator = (By.XPATH, '/html/body/div/div[2]/div/div/div/div[1]/div/a')
        try:
            WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
        except:
            driver.get(urls['urls'])
            return [900001,None,None]
        html = driver.page_source
        pattern = re.compile('<td align="left">(.+?)<\/td>')
        text = pattern.findall(html)
        pattern = re.compile('<td align="center">(.+?)<\/td>')
        daytime = pattern.findall(html)
        detail = {}
        for i in range(len(text)):
            detail[str(i)] = {}
            detail[str(i)]['text'] = text[i]
            detail[str(i)]['time'] = daytime[i]
        code = 2
        for key,values in detail.items():
            if '恭喜您！' in values['text']:
                day = time.mktime(time.strptime(values['time'], '%Y-%m-%d'))
                d_day = time.time()-day
                if d_day//86400 < 90:
                    code = 1
                    break
        return [1,code,detail]    
#6：浦发银行
def pufa_2():
    de_alert()
    new_page(urls['url_06'])
    try:
        opt_dir = get_opt('//*[@id="verifiyImage"]')
    except:
        return [900002,None,None]
    return[1,None,opt_dir]

def pufa_1(idNo,optNo):
    if driver.current_url != urls['url_06']:
        return [1,None,None]
    try:
        driver.find_element_by_id('cardNo').clear()
        driver.find_element_by_id('cardNo').send_keys(idNo)
        driver.find_element_by_name('verifyCode').clear()
        driver.find_element_by_name('verifyCode').send_keys(optNo)
        driver.find_element_by_class_name('searchconarbut').click()
    except:
        return [900000,None,None]
    time.sleep(0.5)
    try:
        alert = driver.switch_to.alert
        message = alert.text
        alert.accept()
        return [900003,None,None]
    except:
        if driver.current_url == urls['url_06']:
            return [900003,None,None]
    if driver.current_url == 'https://www.spdbccc.com.cn/spdb/cupd/applyProgress.do?method=query':        
        try:
            message = driver.find_element_by_class_name('maincontz')
            message = message.text
            go_back()
            return [1,3,None]
        except:
            pass
        time.sleep(0.5)
        html = driver.page_source
        pattern = re.compile('<td height="40" align="center">(.+?)<\/td>')
        info = pattern.findall(html)
        detail = {}
        for i in range(int(len(info)/4)):
            detail[str(i)] = {}
            detail[str(i)]['text']=info[4*i+2]
            detail[str(i)]['time']=info[4*i+3]
            detail[str(i)]['time_apply'] = info[4*i+1]
            detail[str(i)]['card_type'] = info[4*i+0]
        code = 2
        for key,values in detail.items():
            if values['text'] == "申请已通过，后续请留意查收卡片":
                day = time.mktime(time.strptime(values['time'], '%Y-%m-%d'))
                d_day = time.time() - day
                if d_day//86400 < 90:
                    code = 1
                    break
        return [1,code,detail]        
    return [900000,None,None]
#10：上海银行
def shanghai_1(idNo):
    de_alert()
    new_page(urls['url_10'])
    locator = (By.XPATH,'//*[@id="content"]/div/div/div[1]/form/div/button')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
    except:
        return [900001,None,None]
    try:
        driver.find_element_by_xpath('//*[@id="CertificateNo"]').clear()
        driver.find_element_by_xpath('//*[@id="CertificateNo"]').send_keys(idNo)
        driver.find_element_by_xpath('//*[@id="content"]/div/div/div[1]/form/div/button').click()
    except:
        return [900000,None,None]
    locator = (By.XPATH,'//*[@id="content"]/div/div/div[2]/div/div[1]/div/div')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.visibility_of_element_located(locator))
    except:
        return [900001,None,None]
    #time.sleep(5)
    msg = driver.find_element_by_xpath('//*[@id="content"]/div/div/div[2]/div/div[1]/div/div').text
    if msg == '    很抱歉，系统内尚无您的申请信息，建议与原申请渠道确认。\n    ':
        return [1,3,None]
    elif msg == '状态':
        code = 2
        msg = driver.find_element_by_xpath('//*[@id="content"]/div/div/div[2]/div/div[1]/div[1]/div[2]/div[2]').text
        if '已核发' in msg:
            daystr = str(time.localtime(time.time()).tm_year) + msg[7:9] + msg[10:12]
            day = time.mktime(time.strptime(daystr, '%Y%m%d'))
            d_day = time.time()-day
            if d_day//86400 < 90:
                code = 1
    return [1,code,msg]
#12：交通银行
def jiaotong_2():
    de_alert()
    new_page(urls['url_12'])
    locator = (By.XPATH, '//*[@id="vcodec"]')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.visibility_of_element_located(locator))
        opt_dir = get_opt('//*[@id="vcodec"]')
    except:
        return [900002, None, None]
    return [1, None, opt_dir]
def jiaotong_1(idNo, optNo):
    after_url = 'https://creditcardapp.bankcomm.com/member/apply/status/inquiry.html'
#    if driver.current_url != urls['url_12'] or driver.current_url != after_url:
#        return [900000, None, None]
    try:
        driver.find_element_by_xpath('//*[@id="certNo"]').clear()
        driver.find_element_by_xpath('//*[@id="certNo"]').send_keys(idNo)
        driver.find_element_by_xpath('//*[@id="code1"]').clear()
        driver.find_element_by_xpath('//*[@id="code1"]').send_keys(optNo)
        driver.find_element_by_xpath('//*[@id="form1"]/div/table/tbody/tr[4]/td[2]/div/a').submit()
    except:
        return [90000, None, None]
#    locator = (By.XPATH, '//*[@id="contentWrapper-detail"]/div[2]/a')
    try:
        msg = driver.find_element_by_xpath('//*[@id="errormsg"]/p').text
        if '请重新输入' in msg:
            return [900003, None, msg]
    except:
        pass
    try:
#    time.sleep(1)
        msg = driver.find_element_by_xpath('/html/body').find_element_by_xpath('//*[@id="content"]').find_element_by_xpath('/html/body/div/div[1]').find_element_by_xpath('//*[@id="contentWrapper"]').find_element_by_id('contentWrapper-detail').text
        if '很抱歉，没有查询到您的申请记录' in msg:
            return [1, 3, msg]
        else:
            code = 2
            info = msg.split('\n')
            for i, text in enumerate(info):
                if '恭喜您'in text:
                    daystr = text.split('于')[1].split('已')[0]
                    day = time.mktime(time.strptime(daystr, '%Y-%m-%d'))
                    d_day = time.time()-day
                    if d_day//86400 < 90:
                        code = 1
                        break
            return [1, code, info]
    except:
        return [900000, None, None]
#15：中信银行
def zhongxin_3(idNo,phoneNo):
    try:
        de_alert()
        new_page(urls['url_15'])
        try:
            driver.find_element_by_xpath('//*[@id="id_nbr"]').clear()
            driver.find_element_by_xpath('//*[@id="id_nbr"]').send_keys(idNo)
            driver.find_element_by_xpath('//*[@id="mobilePhone"]').clear()
            driver.find_element_by_xpath('//*[@id="mobilePhone"]').send_keys(phoneNo)
            driver.find_element_by_xpath('/html/body/div/div/div/div[2]/div/a').click()
        except:
            return [900000,None,None]
        time.sleep(2)
        if driver.current_url == urls['url_15']:
            time.sleep(2)
            if driver.find_element_by_xpath('/html/body/div/div/div/div[2]/div/a/span').text == '下一步':
                return [900004,None,None]
        else:
            return [1,None,None]
    except:
        driver.get(urls['url0'])
        return [900000,None,None]

def zhongxin_1(verifyNo):
    error_url1 = 'https://creditcard.ecitic.com/citiccard/online/firstPageManage.do?func=sendNewMsg'
    error_url2 = 'https://creditcard.ecitic.com/citiccard/online/firstPageManage.do?func=sendNewMsg#'
    if driver.current_url != error_url1 and driver.current_url != error_url2:
        return [900000,None,None]
    try:
        driver.find_element_by_xpath('//*[@id="msgcode"]').clear()
        driver.find_element_by_xpath('//*[@id="msgcode"]').send_keys(verifyNo)
        driver.find_element_by_xpath('/html/body/div/div/div/div[2]/div/a').click()
    except:
        return [900000,None,None]
    time.sleep(1)
    error_url1 = 'https://creditcard.ecitic.com/citiccard/online/firstPageManage.do?func=sendNewMsg'
    error_url2 = 'https://creditcard.ecitic.com/citiccard/online/firstPageManage.do?func=sendNewMsg#'
    if driver.current_url == error_url1 or driver.current_url == error_url2:
        return [900005,None,None]
    else:
        mode = 1
        while(mode==1):
            html = driver.page_source
            pattern = re.compile('<td>(.*?)<\/td>')
            info = pattern.findall(html)
            detail = {}       
            detail['1'] = {}
            detail['1']['time'] = '2015-07-30'     
            for i in range(int(len(info)/3)):
                detail[str(i)] = {}
                detail[str(i)]['text'] = info[3*i+2]
                detail[str(i)]['time'] = info[3*i+1]
                detail[str(i)]['card_type'] = info[3*i]
            if len(detail)==3 and detail['1']['time'] == '2015-07-30':
                pass
            else:
                mode = 0
        code = 2
        try:
            resmsg = driver.find_element_by_xpath('/html/body/div/div/div/div[2]/div/div').text
            if '没有查询到您的信息' in resmsg:
                return [1,3,None]
        except:
            pass
        for key,values in detail.items():
            if 'text' in values:
                if values['text'] == '您的申请已获批准，感谢您使用中信信用卡！':
                    day = time.mktime(time.strptime(values['time'], '%Y%m%d'))
                    d_day = time.time()-day
                    if d_day//86400 < 90:
                        code = 1
                        break
        return [1,code,detail]
#17:华夏银行
def huaxia_1(idNo, optNo):
    if driver.current_url != urls['url_17']:
        return [900000, None, None]
    driver.find_element_by_xpath('//*[@id="MemberId"]').clear()
    driver.find_element_by_xpath('//*[@id="MemberId"]').send_keys(idNo)
    driver.find_element_by_xpath('//*[@id="_vTokenName"]').clear()
    driver.find_element_by_xpath('//*[@id="_vTokenName"]').send_keys(optNo)
    driver.find_element_by_xpath('//*[@id="button2"]').click()
    time.sleep(10)
    try:
        driver.find_element_by_xpath('/html/body/div[3]/div/div[1]/div/form/center[1]/p')
    except:
        return [900003, None, None]
    table = driver.find_element_by_xpath('/html/body/div[3]/div/div[1]/div/form/center[2]/table')
    msg = table.text.split('\n')[1].split(' ')[2]
    if msg == '已产生卡片':
        return [1, 1, msg]
    else:
        return [1, 2, msg]
    return[900000, None, None]


def huaxia_2():
    de_alert()
    new_page(urls['url_17'])
    locator = (By.XPATH, '//*[@id="_tokenImg"]')
    try:
        WebDriverWait(driver, 20, 0.5).until(EC.visibility_of_element_located(locator))
        opt_dir = get_opt('//*[@id="_tokenImg"]')
    except:
        return [900002, None, None]
    return [1, None, opt_dir]
